package com.android.qjpmc.widget.recyclerView;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.android.qjpmc.databinding.ViewRefreshRecyclerviewLayoutTestBinding;
import com.android.qjpmc.R;
import com.android.qjpmc.constant.Constant;
import com.android.qjpmc.widget.base.BaseRefreshViewLayout;
import com.android.qjpmc.widget.bean.BaseListData;
import com.android.qjpmc.widget.bean.BaseRequestData;
import com.android.qjpmc.widget.manager.RxJavaHttpManager;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.ProgressObserver;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;


/**
 * Created by Administrator on 2017/4/15 0015.
 */

public class RefreshRecyclerViewLayout extends BaseRefreshViewLayout<ViewRefreshRecyclerviewLayoutTestBinding> {


    private RefreshRecyclerNetConfig netConfig;
    private List secondPageListData;
    private boolean isAutoLoadTriggerOnLoadMore;

    public RefreshRecyclerViewLayout(@NonNull Context context) {
        super(context);
    }

    public RefreshRecyclerViewLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void initView(Context context, AttributeSet attrs) {
        super.initView(context, attrs);
        setRefreshLayout(mBinding.refreshLayout);
        // mBinding.refreshLayout.setRefreshContent(mBinding.baseRecyclerView);
    }

    @Override
    public void initEvent(Context context) {
        super.initEvent(context);
        getRefreshLayout().setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                RefreshRecyclerViewLayout.this.onLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                RefreshRecyclerViewLayout.this.onRefresh();
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_refresh_recyclerview_layout_test;
    }

    private io.reactivex.Observable observable;

    @Override
    public void requestNetEmpty() {
        switch (action) {
            case ACTION_FIRST_LOAD:
                showPageEmpty();
                break;
            case ACTION_REFRESH:
                showPageEmpty();
                finishHeadRefresh();
                if (mBuilder.getAdapter() != null) {
                    mBuilder.getAdapter().clear();
                }
                break;
            case ACTION_LOAD_MORE:
                finishFootLoadMore();
                break;
            case ACTION_SECOND_LOAD_MORE:
                setIsLoaderMoreSecondPageEmpty(true);
                break;
            case ACTION_PAGE_REFRESH:
                showPageEmpty();
                if (mBuilder.getAdapter() != null) {
                    mBuilder.getAdapter().clear();
                }
                break;
        }
        super.requestNetEmpty();

    }

    @Override
    public void requestNetError(String errorInfo, int errorCode) {
        super.requestNetError(errorInfo, errorCode);
        if (TextUtils.isEmpty(errorInfo)) {
            errorInfo = "页面加载失败,请稍后重试";
        }
        setErrorMsg(errorInfo);
        switch (action) {
            case ACTION_FIRST_LOAD:
                currentPage = 1;
                showPageError();
                break;
            case ACTION_REFRESH:
                currentPage = 1;
                finishHeadRefresh();
                if (mBuilder.getAdapter() != null) {
                    mBuilder.getAdapter().clear();
                }
                break;
            case ACTION_LOAD_MORE:
                finishFootLoadMore();
                break;
            case ACTION_SECOND_LOAD_MORE:
                setIsLoaderMoreSecondPageError(true);
                break;
            case ACTION_PAGE_REFRESH:
                break;
        }
    }

    @Override
    public void requestNetStart(Disposable d) {
        super.requestNetStart(d);
        switch (action) {
            case ACTION_FIRST_LOAD:
                initPageManager();
                mRecyclerPageManger.showPageLoading(d);
                break;
            case ACTION_SECOND_LOAD_MORE:
                setIsLoaderMoreSecondPageIng(true);
                break;
            case ACTION_PAGE_REFRESH:
                break;
        }
    }

    @Override
    public void requestNetSuccess(List listInfoPojos) {
        super.requestNetSuccess(listInfoPojos);
        switch (action) {
            case ACTION_PAGE_REFRESH:
            case ACTION_FIRST_LOAD:
                isFirstIn = false;
                currentPage = 1;
                mBuilder.getAdapter().refresh(listInfoPojos);
                if (listInfoPojos.size() >= COUNT) {
                    onLoadMoreSecondPage();
                }
                showPageContent();
                break;
            case ACTION_REFRESH:
                showPageContent();
                currentPage = 1;
                if (listInfoPojos != null && listInfoPojos.size() != 0) {
                    mBuilder.getAdapter().refresh(listInfoPojos);
                }
                finishHeadRefresh();
                if (listInfoPojos.size() >= COUNT) {
                    onLoadMoreSecondPage();
                }

                break;
            case ACTION_LOAD_MORE:

                if (listInfoPojos != null && listInfoPojos.size() != 0) {
                    currentPage++;
                    mBuilder.getAdapter().addAll(listInfoPojos);
                }
                onLoadMoreSecondPage();
                finishFootLoadMore();
                break;
            case ACTION_TOP_LOAD_MORE:
                currentPage++;
                if (listInfoPojos != null && listInfoPojos.size() != 0) {
                    mBuilder.getAdapter().addAllTop(listInfoPojos);
                }
                break;
            case ACTION_SECOND_LOAD_MORE:
                currentPage++;
                if (secondPageListData != null)
                    secondPageListData.clear();
                setIsLoaderMoreSecondPageIng(false);
                if (!isAutoLoadTriggerOnLoadMore) {
                    secondPageListData = listInfoPojos;
                    setIsLoaderMoreSecondPageSuccess(true);
                } else {
                    isAutoLoadTriggerOnLoadMore = false;
                    mBuilder.getAdapter().addAll(listInfoPojos);
                    setIsLoaderMoreSecondPageSuccess(false);
                    if (listInfoPojos.size() >= COUNT)
                        onLoadMoreSecondPage();
                }
                break;
        }

    }


    public void requestNetObjectSuccess(List list, int action) {
        if (list == null || list.size() == 0) {
            requestNetEmpty();
        } else {
            requestNetSuccess(list);
        }
    }

    @Override
    public void onRefresh() {
        action = ACTION_REFRESH;
        setRefreshDataNotShowLoading(false);
        if (mBuilder.isRefreshCallBack()) {
            mRefreshLoadMoreListener.onRefresh();
        } else {
            onRequestRefreshData();
        }

    }

    @Override
    public void onLoadMore() {
        if (mBuilder.isLoadMoreSecondPage()) {
            if (mBuilder.isLoaderMoreSecondPageSuccess()) {
                mBuilder.getAdapter().addAll(secondPageListData);
                setIsLoaderMoreSecondPageIng(false);
                setIsLoaderMoreSecondPageSuccess(false);
                if (secondPageListData.size() >= COUNT)
                    onLoadMoreSecondPage();
            } else if (mBuilder.isLoaderMoreSecondPageIng()) {
                isAutoLoadTriggerOnLoadMore = true;
                return;
            }
        }
        setRefreshDataNotShowLoading(false);
        action = ACTION_LOAD_MORE;
        if (mBuilder.isLoadMoreCallBack()) {
            mRefreshLoadMoreListener.onLoadMore();
        } else {
            onRequestLoadMoreData();
        }
    }

    @Override
    public void firstLoad() {
        super.firstLoad();
        action = ACTION_FIRST_LOAD;
        setRefreshDataNotShowLoading(false);
        requestNet(1);
    }

    @Override
    public void refresh() {
        super.refresh();
        action = ACTION_PAGE_REFRESH;
        setRefreshDataNotShowLoading(true);
        requestNet(1);
    }

    public void onRequestRefreshData() {
        requestNet(1);
    }

    public void onRequestLoadMoreData() {
        requestNet(currentPage + 1);
    }

    public void onLoadMoreSecondPage() {
        if (!mBuilder.isLoadMoreSecondPage())
            return;
        action = ACTION_SECOND_LOAD_MORE;
        setRefreshDataNotShowLoading(false);
        setLoadMoreDataNotShowLoading(false);
        setIsLoaderMoreSecondPageIng(true);
        loadMoreSecondPage(true);
        requestNet(currentPage + 1);
    }


    @Override
    public RecyclerView getRecyclerView() {
        return mBinding.baseRecyclerView;
    }

    private void requestNet(int page) {
        Map<String, Object> mapParams = new HashMap<>();
        mapParams.put(Constant.PAGE_SIZE, Constant.PAGE_VALUE);
        mapParams.put(Constant.PAGE, page);
        // config.addNetParams(mapParams);
        if (netConfig == null) {
            initPageManager();
            mRecyclerPageManger.showPageError();
            return;
        }
        createBuilder();
        setRefreshLoaderMore(mBuilder.isRefresh(), mBuilder.isLoadMore());
        observable = netConfig.getNetObservable(mapParams, action);

        if (mBuilder.isDataObject()) {
            observable.compose(RxJavaHttpManager.applyTransformer()).subscribe(new ProgressObserver(false, false, false, null) {
                @Override
                public void _onNext(Object o) {
                    if (o == null) {
                        requestNetEmpty();

                    } else {
                        if (mRefreshRecyclerLoadStatusListener != null) {
                            mRefreshRecyclerLoadStatusListener.onSucceed(o, action);
                        }
                    }
                }

                @Override
                public void _onError(String errorMessage, int errorCode) {
                    super._onError(errorMessage, errorCode);
                    requestNetError(errorMessage, errorCode);
                }

                @Override
                public void onSubscribe(Disposable d) {
                    super.onSubscribe(d);
                    Logger.d("onSubscribe : " + Thread.currentThread().getName());
                    requestNetStart(d);
                }

            });
        } else {

            observable.compose(RxJavaHttpManager.<BaseRequestData<BaseListData>>applyTransformer()).subscribe(new ProgressObserver<BaseListData<Object>>(false, false, false, null) {
                @Override
                public void _onNext(BaseListData o) {
                    if (o == null || o.data.size() == 0) {
                        requestNetEmpty();

                    } else {
                        requestNetSuccess(o.data);
                        if (mRefreshRecyclerLoadStatusListener != null) {
                            mRefreshRecyclerLoadStatusListener.onSucceed(o, action);
                        }
                    }

                }

                @Override
                public void _onError(String errorMessage, int errorCode) {
                    super._onError(errorMessage, errorCode);
                    if (errorCode != 1001)
                        requestNetError(errorMessage, errorCode);
                }

                @Override
                public void onSubscribe(Disposable d) {
                    super.onSubscribe(d);
                    requestNetStart(d);
                }

            });

        }
    }

    public void setRefreshRecyclerNetConfig(RefreshRecyclerNetConfig netConfig) {
        this.netConfig = netConfig;
    }

    public void initNormalScrollListener() {
/*
        getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {


            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (isSlideToBottom(recyclerView)) {

                    getRefreshLayout().setNestedScrollingEnabled(true);
                    getRefreshLayout().setEnableOverScroll(false);
                    setRefreshLoaderMore(false, true);
                } else {
                    getRefreshLayout().setNestedScrollingEnabled(false);
                    getRefreshLayout().setEnableOverScroll(false);
                    setRefreshLoaderMore(false, false);
                }
            }
        });
*/

    }

    public void setShowEmptyLoginButton(boolean b) {
        createBuilder();
        mBuilder.setShowEmptyLoginButton(b);
    }
}
